<template>
  <div
    class="real-time-toggle"
    @click="
      () => {
        toggleRealTimeLayer()
        showVideoDialog()
      }
    "
  >
    {{ trafficLayerVisible ? '隐藏实时路况' : '显示实时路况' }}
  </div>
  <div
    v-if="videoDialogVisible"
    class="video-dialog-mask"
    @click.self="videoDialogVisible = false"
  >
    <div class="video-dialog">
      <h3>{{ currentRoadName }}</h3>
      <video
        :src="currentVideoUrl"
        controls
        autoplay
        style="width: 400px; max-width: 90vw"
      />
      <div style="text-align: right; margin-top: 8px">
        <button @click="videoDialogVisible = false">关闭</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, inject } from 'vue'

const props = defineProps({})

const map = inject('mapInstance', ref(null))

const trafficLayer = ref(null)
const trafficLayerVisible = ref(false)

const videoDialogVisible = ref(false)
const currentVideoUrl = ref('')
const currentRoadName = ref('')

const showVideoDialog = () => {
  currentVideoUrl.value = new URL('/example.mp4', import.meta.url).pathname
  currentRoadName.value = '实时路况视频演示'
  videoDialogVisible.value = true
}

// 模拟的实时路况数据 (GeoJSON LineString)
const mockTrafficData = {
  type: 'FeatureCollection',
  features: [
    {
      type: 'Feature',
      geometry: {
        type: 'LineString',
        coordinates: [
          [114.305, 30.593], // 武汉长江大桥附近
          [114.312, 30.595],
          [114.32, 30.6],
        ].map((coord) => ol.proj.fromLonLat(coord)),
      },
      properties: {
        id: 'road1',
        name: '长江大桥',
        status: 'congested',
        videoUrl: new URL('/example.mp4', import.meta.url).pathname,
      },
    },
    {
      type: 'Feature',
      geometry: {
        type: 'LineString',
        coordinates: [
          [114.34, 30.545], // 武汉光谷广场附近
          [114.345, 30.55],
          [114.35, 30.555],
        ].map((coord) => ol.proj.fromLonLat(coord)),
      },
      properties: {
        id: 'road2',
        name: '光谷广场',
        status: 'moderate',
        videoUrl: new URL('/example.mp4', import.meta.url).pathname,
      },
    },
    {
      type: 'Feature',
      geometry: {
        type: 'LineString',
        coordinates: [
          [114.27, 30.61], // 武汉汉口火车站附近
          [114.275, 30.615],
          [114.28, 30.62],
        ].map((coord) => ol.proj.fromLonLat(coord)),
      },
      properties: {
        id: 'road3',
        name: '汉口火车站',
        status: 'clear',
        videoUrl: new URL('/example.mp4', import.meta.url).pathname,
      },
    },
  ],
}

const getTrafficStyle = (feature) => {
  const status = feature.get('status')
  let color = 'blue'
  if (status === 'moderate') {
    color = 'yellow'
  } else if (status === 'congested') {
    color = 'red'
  }
  return new ol.style.Style({
    stroke: new ol.style.Stroke({
      color: color,
      width: 6,
    }),
  })
}

const createTrafficLayer = () => {
  if (!map.value) {
    console.warn('地图实例未提供给 RealTime 组件')
    return null
  }
  const vectorSource = new ol.source.Vector({
    features: new ol.format.GeoJSON().readFeatures(mockTrafficData),
  })

  return new ol.layer.Vector({
    source: vectorSource,
    style: getTrafficStyle,
    title: 'RealTimeTrafficLayer',
  })
}

const toggleRealTimeLayer = () => {
  if (!map.value) return
  if (!trafficLayer.value) {
    trafficLayer.value = createTrafficLayer()
    if (trafficLayer.value) {
      map.value.addLayer(trafficLayer.value)
      trafficLayerVisible.value = true
    }
  } else {
    trafficLayer.value.setVisible(!trafficLayerVisible.value)
    trafficLayerVisible.value = !trafficLayerVisible.value
  }
}

const refreshTrafficData = () => {
  if (trafficLayer.value && trafficLayerVisible.value) {
    console.log('刷新路况数据...')
    const source = trafficLayer.value.getSource()
    const features = source.getFeatures()
    features.forEach((feature) => {
      const statuses = ['clear', 'moderate', 'congested']
      const newStatus = statuses[Math.floor(Math.random() * statuses.length)]
      feature.set('status', newStatus)
    })
  }
}

onMounted(() => {
  if (map.value) {
    map.value.on('singleclick', function (evt) {
      if (!trafficLayer.value || !trafficLayerVisible.value) return
      const feature = map.value.forEachFeatureAtPixel(evt.pixel, (f) => f)
      if (feature && feature.get('videoUrl')) {
        currentVideoUrl.value = feature.get('videoUrl')
        currentRoadName.value = feature.get('name')
        videoDialogVisible.value = true
      }
    })
  }
  setInterval(refreshTrafficData, 30000)
})

watch(
  () => map.value,
  (newMap) => {
    if (newMap && trafficLayerVisible.value && !trafficLayer.value) {
      toggleRealTimeLayer()
    }
  }
)
</script>

<style scoped lang="scss">
.real-time-toggle {
  padding: 8px 15px;
  background-color: #409eff;
  color: white;
  border-radius: 4px;
  cursor: pointer;
  text-align: center;
  margin: 10px;
  display: inline-block;
}

.real-time-toggle:hover {
  background-color: #66b1ff;
}

.video-dialog-mask {
  position: fixed;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.4);
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
}

.video-dialog {
  background: #fff;
  border-radius: 8px;
  padding: 24px 20px 16px 20px;
  min-width: 320px;
  box-shadow: 0 2px 16px rgba(0, 0, 0, 0.18);
}
</style>
